/*
 * Copyright @ 苏州瑞云信息技术有限公司 All rights reserved.
 */
package work.xml.dom4j;

import org.dom4j.*;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.util.Iterator;
import java.util.List;

/**
 * @author Sakura Shen
 *
 * org.dom4j包的使用
 * 解析xml文件
 *
 * @date 2021/8/26
 */
public class Dom4jTest01 {

    public static void main(String[] args) {
        dom4j();
    }

    public static void dom4j() {
        parseDom4j(new File("E:\\dom4j.xml"));
    }


    /**
     * 解析xml文件 读取文件中的各个节点的数据
     * @param file
     */
    public static void parseDom4j(File file) {
        try {
            // 创建一个SAXReader解析器
            SAXReader reader = new SAXReader();

            // 读取xml文件,转换成Document结点
            Document doc = reader.read(file);

            // 递归打印xml文档信息
            StringBuffer buffer = new StringBuffer();
            parseElement(doc.getRootElement(), buffer);
            System.out.println(buffer.toString());
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


    /**
     * 递归解析XML 是个递归方法
     * @param element
     * @param buffer
     */
    @SuppressWarnings("unchecked")
    public static void parseElement(Element element, StringBuffer buffer) {
        buffer.append("<"+element.getName());
        List<Attribute> attrs = element.attributes();
        if (attrs != null) {
            for (Attribute attr : attrs) {
                buffer.append(" "+attr.getName()+"=\""+attr.getValue()+"\"");
            }
        }
        buffer.append(">");

        Iterator<Node> iterator = element.nodeIterator();
        while (iterator.hasNext()) {
            Node node = iterator.next();
            if (node instanceof Element) {
                Element eleNode = (Element) node;
                parseElement(eleNode, buffer);
            }
            if (node instanceof Text) {
                Text text = (Text) node;
                buffer.append(text.getText());
            }
            if (node instanceof CDATA) {
                CDATA dataNode = (CDATA) node;
                buffer.append(dataNode.getText());
            }
            if (node instanceof Comment) {
                Comment comNode = (Comment) node;
                buffer.append(comNode.getText());
            }
        }
        buffer.append("</"+element.getName()+">");
    }


}
